package com.lianwei.interceptor;

import com.lianwei.enums.UserCodeEnum;
import com.lianwei.pojo.LoginUser;
import com.lianwei.util.CommonUtil;
import com.lianwei.util.JWTUtil;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*
 *@ClassName LoginInterceptor
 *@Description TODO
 *@Author Kuiwen.Sun
 *@Date 2022/1/11 9:56
 *@Version 1.0
 */
public class LoginInterceptor implements HandlerInterceptor {
    public static ThreadLocal<LoginUser> userThreadLocal = new InheritableThreadLocal<>();
      public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
          System.out.println("进入拦截器");
          String token = request.getHeader("token");
          token = token == null ? request.getParameter("token") : token;
          if (token==null){
              CommonUtil.sendJsonMessage(response,UserCodeEnum.ACCOUNT_UNLOGIN);
              return false;
          }
          Claims claims = JWTUtil.checkJWT(token);
          if (claims==null){
             CommonUtil.sendJsonMessage(response,UserCodeEnum.ACCOUNT_UNLOGIN);
             return false;
          }
          Long id = Long.valueOf(String.valueOf(claims.get("id")));
          String headImg = claims.get("headImg") == null ? "" : claims.get("headImg").toString();
          String name = claims.get("username") == null ? "" : claims.get("username").toString();
          String mail = claims.get("mail") == null ? "" : claims.get("mail").toString();
          LoginUser loginUser = LoginUser.builder().id(id).username(name).headImg(headImg).mail(mail).build();
          userThreadLocal.set(loginUser);
          return true;
    }

}
